<template>
  <div class="container-content">
    <div class="container-content-left tree-container">
      <el-form ref="treeSearchForm" :inline="true" :model="treeSearchForm" :size="size">
        <el-form-item prop="keyword">
          <el-input v-model="treeSearchForm.keyword" placeholder="请输入关键词" clearable>
            <el-button slot="append" :size="size" icon="el-icon-search" @click="getCompanysTree"/>
          </el-input>
        </el-form-item>
      </el-form>
      <rf-edit-tree :data="treeList" :menuPermission="menuPermission" :showEdit="false" :default-props="defaultProps" :default-keys="defaultKeys" @addChild="addChild"
        @editNode="editNode" @deleteNode="deleteNode" @nodeClick="nodeClick" />
    </div>
    <div class="container-content-right">
      <div class="container-content-header">
        <el-form ref="searchForm" :inline="true" :model="searchForm" :size="size">
          <el-form-item prop="name">
            <el-input v-model="searchForm.keyword" placeholder="请输入关键词" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="init">
              搜索
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="container-content-main">
        <div class="operation">
          <el-button type="normal" v-has="btn_sync_data" :size="size" @click="syncData" :loading="loadingSync">数据同步</el-button>
        </div>
        <!--<div class="tableTips">
          <i class="icon el-icon-warning"></i>
          已选择 <span style="color: #0890ea; margin: 0 5px">{{sels.length}}</span> 项
        </div>-->
        <el-table style="width: 100%;" :data="tableList" @selection-change="selsChange" fit border highlight-current-row
          :size="size" row-key="id" reserve-selection>
          <!--<el-table-column type="selection" width="50" align="center"></el-table-column>-->
          <el-table-column prop="userKey" label="账号" align="center" min-width="100" />
          <el-table-column prop="realName" label="姓名" align="center" min-width="80" />
          <el-table-column prop="phone" label="手机号码" align="center" min-width="120" />
          <el-table-column prop="email" label="邮箱" align="center" show-overflow-tip min-width="120" />
          <el-table-column prop="companys" label="归属组织" align="center" show-overflow-tooltip min-width="120" />
          <el-table-column prop="status" label="状态" align="center" min-width="60">
            <template slot-scope="{row}">
               <el-tag size="small" :type="statusArr[row.status].type">{{ statusArr[row.status].label }}</el-tag>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="searchForm.page" :limit.sync="searchForm.limit"
          @pagination="init" />
      </div>

      <!-- 新增编辑人员弹框 -->
      <el-dialog class="question-dialog" :title="dialogEdit ? '编辑' : '新增'"
        :visible.sync="isDialogShow" :close-on-click-modal="closeOnclickModal" @close="closeDialog">
        <el-form ref="dialogForm" :model="dialogForm" :size="size" label-width="120px">
          <el-form-item label="账号:" :rules="rf_rules({required:true})" prop="userKey">
            <el-input v-model="dialogForm.userKey" placeholder="请输入账号" clearable />
          </el-form-item>
          <el-form-item label="姓名:" :rules="rf_rules({required:true})" prop="realName">
            <el-input v-model="dialogForm.realName" placeholder="请输入姓名" clearable />
          </el-form-item>
          <el-form-item label="性别:" :rules="rf_rules({required:true})" prop="sex">
            <el-radio-group v-model="dialogForm.sex">
              <el-radio :label="0">男</el-radio>
              <el-radio :label="1">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="手机号码:" :rules="rf_rules({required:true, type: 'phone'})" prop="phone">
            <el-input v-model="dialogForm.phone" placeholder="请输入手机号码" clearable />
          </el-form-item>
          <el-form-item label="邮箱:" :rules="rf_rules({type: 'email'})" prop="email">
            <el-input v-model="dialogForm.email" placeholder="请输入邮箱" clearable />
          </el-form-item>
          <el-form-item label="归属部门:" prop="deptId">
            <el-select v-model="dialogForm.deptId" style="width: 100%;" clearable>
              <el-option v-for="item in deptList" :key="item.id" :label="item.fullName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="归属组织:" prop="companyIdList">
            <el-tag class="rf-tag-item" v-for="(tag, index) in dialogForm.companyList" :key="tag.id" :size="size">
              {{tag.fullName}}
            </el-tag>
            <el-button :size="size" type="primary" @click="chooseOrg">选择</el-button>
          </el-form-item>
          <el-form-item label="状态:" :rules="rf_rules({required:true})" prop="status">
            <el-radio-group v-model="dialogForm.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button :size="size" @click="closeDialog">取消</el-button>
          <el-button type="primary" :size="size" @click="submit">确定</el-button>
        </span>
      </el-dialog>

      <!-- 新增编辑分类弹框 -->
      <el-dialog class="custom-form-dialog" :title="treeDialogEdit ? '编辑' : '新增'"
        :visible.sync="isDialogTreeShow" :close-on-click-modal="closeOnclickModal" @close="closeTreeDialog">
        <el-form ref="dialogTreeForm" :model="dialogTreeForm" :size="size" label-width="120px">
          <el-form-item label="组织名称" :rules="rf_rules({required:true})" prop="fullName">
            <el-input v-model="dialogTreeForm.fullName" :placeholder="$t('请输入组织名称')" clearable />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button :size="size" @click="closeTreeDialog">取消</el-button>
          <el-button type="primary" :size="size" @click="submitTree">确定</el-button>
        </span>
      </el-dialog>
    </div>
    <OrgDialogSelect ref="orgDialogSelect" :isDialogOrgShow.sync="isDialogOrgShow" @choose="selectOrg"></OrgDialogSelect>
  </div>
</template>

<script>
  import {mapGetters} from "vuex"
  import OrgDialogSelect from '@/components/DialogSelect/organization'
  import RfImportFile from '@/components/Upload/RfImportFile'
  import api from '@/utils/api.js'
  import Pagination from "@/components/Pagination";
  import RfUploadFile from "@/components/Upload/RfUploadFile";

  export default {
    name: '/businessManager/userorg',
    components: {
      Pagination,
      RfUploadFile,
      OrgDialogSelect,
      RfImportFile
    },
    data () {
      return {
        treeSearchForm: {
          keyword: ''
        },
        searchForm: {
          keyword: '',
          page: 1,
          limit: 10,
          companyId: '',
          ancestors: '',
          stat: true
        },
        tableList: [],
        total: 0,
        dialogForm: {
          companyList: [],
          companyIdList: [],
          email: "",
          id: "",
          phone: "",
          realName: "",
          sex: 0,
          status: 1,
          userKey: "",
          deptId: ''
        },
        isDialogShow: false,
        dialogEdit: false,
        isDialogTreeShow: false,
        treeDialogEdit: false,
        defaultKeys: [0],
        menuPermission: ['btn_company_add', 'btn_company_edit', 'btn_company_delete'],
        dialogTreeForm: {
          id: 0,
          parentId: "",
          fullName: ""
        },
        defaultProps: {
          children: "childNodes",
          label: "text",
          value: "id"
        },
        treeList: [],
        isDialogOrgShow: false,
        statusArr: [{
          label: '禁用',
          type: 'danger'
        },{
          label: '启用',
          type: ''
        }],
        sels: [],
        updateConfig: {
          tip: {
            'enableRole': this.$t('TIP.ENABLE_CONFIRM_TXT'),
            'disableRole': this.$t('TIP.DISABLE_CONFIRM_TXT')
          },
          status: {
            'enableRole': 1,
            'disableRole': 0
          }
        },
        deptList: [],
        isImportShow: false,
        loadingSync: false
      }
    },
    watch: {},
    computed: {
      ...mapGetters(["size", "closeOnclickModal", "userInfo"]),
    },
    mounted () {
      this.init()
      this.getCompanysTree()
    },
    methods: {
      // 导入
      importData () {
        this.isImportShow = true
      },
      // 数据同步
      syncData () {
        this.loadingSync = true
        api.syncData().then(res => {
          this.$message.success(this.$t("同步数据成功"))
          this.loadingSync = false
        }).catch(res => {

        })
      },
      // 获取部门列表
      getDeptList () {
        api.getDepartmentsAllList().then(res => {
          this.deptList = res.data
        })
      },
      selsChange (data) {
        this.sels = data
      },
      chooseOrg () {
        this.isDialogOrgShow = true
        this.$nextTick(() => {
          this.$refs.orgDialogSelect.setSelectedList(this.dialogForm.companyList)
        })
      },
      selectOrg (data) {
        this.dialogForm.companyIdList = data.map(item => {
          return item.id
        })
        this.dialogForm.companyList = data
      },
      // 获取组织树
      getCompanysTree () {
        api.getCompanysTreeAjax(this.treeSearchForm).then(res => {
          this.treeList = res.data
          this.defaultKeys = [res.data[0].id]
        })
      },
      // 添加子树
      addChild (data, node) {
        this.isDialogTreeShow = true
        this.treeDialogEdit = false
        delete this.dialogTreeForm.id
        this.dialogTreeForm.parentId = data.id
      },
      // 提交子树
      submitTree () {
        this.validateSubmit("dialogTreeForm")
          .then(() => {
            const params = this.dialogTreeForm
            api.saveOrUpdateCompanysAjax(params).then(res => {
              this.$message.success('操作成功')
              this.closeTreeDialog()
              this.getCompanysTree()
            })
          })
          .catch(() => {})
      },
      // 修改子树
      editNode (data, node) {
        this.treeDialogEdit = true
        if (node.level === 1) {
          this.$message.warning(this.$t("请不要修改根节点"))
        } else {
          this.dialogTreeForm.fullName = data.text
          this.dialogTreeForm.id = data.id
          this.dialogTreeForm.parentId = data.parentId
          this.isDialogTreeShow = true
        }
      },
      // 删除节点
      deleteNode (data, node) {
        if (node.level === 1) {
          this.$message.warning(this.$t("请不要删除根节点"))
        } else {
          this.delConfirm().then(() => {
            api.deleteCompanysAjax({id: data.id}).then(res => {
              this.getCompanysTree()
            })
          })
        }
      },
      // 初始化用户列表
      init () {
        const params = this.searchForm
        api.getUsersAjax(params).then(res => {
          this.tableList = res.data.list
          this.total = res.data.count
        })
      },

      // 提交用户
      submit () {
        this.validateSubmit("dialogForm").then(() => {
          const params = this.dialogForm
          api.saveOrUpdateUsersAjax(params).then(res => {
            this.$message.success(this.$t("操作成功"))
            this.closeDialog()
            this.init()
          })
        }).catch(() => {})
      },

      // 点击树节点后查询
      nodeClick (data) {
        this.searchForm.companyId = data.id;
        this.searchForm.ancestors = data.path;
        this.init()
      },
      // 新增用户
      add () {
        this.dialogEdit = false
        this.isDialogShow = true
        if (this.deptList.length <= 0) {
          this.getDeptList()
        }
        delete this.dialogForm.id
      },
      // 编辑用户
      edit (row) {
        this.dialogEdit = true
        this.isDialogShow = true
        if (this.deptList.length <= 0) {
          this.getDeptList()
        }
        api.getUserDetail(row.id).then(res => {
          this.dialogForm = Object.assign(this.dialogForm, res.data)
          this.dialogForm.companyIdList = res.data.companyList.map(item => item.id)
        })
      },
      // 批量删除
      deleteUser (type, userId) {
        const id = type === 'batch' ? this.sels.map(item => item.id).join(',') : userId
        const params = {
          id
        }
        this.delConfirm().then(() => {
          api.deleteUser(params).then(res => {
            this.$message.success('操作成功')
            this.init()
          })
        })
      },
      // 更新角色状态
      updateStatus (row) {
        const scene = row.status === 1 ? 'disableRole' : 'enableRole'
        const tip = this.updateConfig.tip[scene]
        this.delConfirm(tip, this.$t('TIP.TIP')).then(() => {
          const params = {
            id: row.id,
            status: this.updateConfig.status[scene]
          }
          api.updateUserStatus(params).then(res => {
            this.$message.success('操作成功')
            this.init()
          })
        })
      },
      // 关闭分类弹框
      closeTreeDialog () {
        this.$refs["dialogTreeForm"].resetFields()
        this.isDialogTreeShow = false
      },
      // 关闭组织弹框
      closeDialog () {
        this.$refs["dialogForm"].resetFields()
        this.dialogForm.companyList = []
        this.isDialogShow = false
      }
    }
  };
</script>

<style lang="scss">
  .question-dialog {
    .el-dialog {
      width: 30%;
      min-width: 450px;
    }
  }

  .tree-container {
    min-width: 250px;
    overflow: auto;
  }
</style>
